<?php

namespace app\common\service;

use Firebase\JWT\JWT;

class TokenService
{
    public $config = [];
    public function __construct()
    {
        $this->config = config("token");
    }

    /**
     * 生成token
     * @param $user
     * @return string
     */
    public function create($user)
    {
        $key = $this->config['token_key']; //秘钥
        $iat = time();//签发时间
        $nbf = time();//生效时间
        $exp = time() + $this->config['token_exp'] * 3600;//过期时间
        $data = [
            'user_id' => $user['id']
        ];
        $payload = [
            'iat' => $iat,
            'nbf' => $nbf,
            'exp' => $exp,
            'data' => $data
        ];
        $token = JWT::encode($payload, $key);
        return $token;
    }
    public function verify($token){
        try {
            $decode = JWT::decode($token, $this->config['token_key'], array('HS256'));
            $user_id = $decode->data->user_id;
        } catch (\Exception $e) {
            $user_id =0;
        }
        return $user_id;
    }
}